import React, { useState,useRef,useEffect } from 'react';  
import { Steps, Card, Row, Col,Form,Button,Input,Modal,Select,List,Table, message,Upload,Tooltip  } from 'antd';
import { UploadOutlined } from '@ant-design/icons';   
import './LiterdataDetail.css'; // 引入自定义样式  
import MemoTable from '@/components/MemoTable';
import { useTranslation } from 'react-i18next';
import { addRemark,updateRemark,delRemark} from "@/api/modules/remarks";
import { listIngredient,del,add,edit,getIngredientInfoById,delReport,delScreen,addReport,editReport,addScreen,editScreen,importReport} from "@/api/modules/literdata";
import { getIngredientSubjectTestById,comparisonIngredient,importIngredientInfoCheck,importIngredientInfoSave} from "@/api/modules/litermark";
import { list} from "@/api/modules/inci";
import MyTabsComponent from '../literMark/MyTabsComponent';
import { useNavigate  } from 'react-router-dom';
import { upload } from "@/api/modules/common";
import useCurrentPage from '@/store/modules/currentPage'
import useHistoryTags, {HistoryTag} from '@/store/modules/historyTags'
import useDynamicCache from '@/store/modules/dynamicCache'
import useCacheAlive from '@/hooks/useCacheAlive'
import { getInfo } from "@/api/login/ssoLogin";

const { Step } = Steps;  
const { Option } = Select;  

const LiterdataDetail = () => {  
  const { t } = useTranslation()
  const navigate = useNavigate();
  const currentPage = useCurrentPage()
  const [currentStep, setCurrentStep] = useState(0);  
  const [isModalVisible, setIsModalVisible] = useState(false); 
  const [Title, setTitle] = useState("")  
  const [form] = Form.useForm();  
  const [form2] = Form.useForm();  
  const [formCache,setformCache] = useCacheAlive({}, `table-literdataDetail-formCache`)
  const [fileList, setFileList] = useState([]); 
  const [filename, setFilename] = useState("");
  const [reportlist,setReportlist] = useState([]);
  const [screenlist,setScreenlist] = useState([]);
  const [remarkslist,setRemarkslist] = useState([]);
  const [isView, SetisView] = useState(false)
  const [onReloadNum, setReloadNum] = useState(null); 
  const [tabData,setTabData] = useState([]);
  const [tabSubjectLevel1,setTabSubjectLevel1] = useState([])
  const [formId,setFormId]  = useState(null)
  const [zyNo,setZYNo]  = useState(null)
  const [formReport] = Form.useForm();  
  const [reportvisible, setReportVisible] = useState(false);  
  const [formFulu] = Form.useForm();  
  const [fuluvisible, setFuluVisible] = useState(false);  
  const [viewStatus, setViewStatus] = useState(false); // 加载状态 


 // 创建refs来引用Card元素  
 const cardRef1 = useRef(null);  
 const cardRef2 = useRef(null);  
 const cardRef3 = useRef(null);  
 const cardRef4 = useRef(null); 
  const maodianlist = [  
    '基础属性',  
    '文献',  
    '附录',  
    '毒理学终点',  
  ];  

  const getQueryVariable = (variable) =>{
    const query = window.location.search.substring(1);
    const vars = query.split("&");
    for (let i = 0; i < vars.length; i++) {
        let pair = vars[i].split("=");
        if (pair[0] == variable) { return pair[1]; }
    }
    return (false);
  }
  
  // 滚动到指定Card的函数  
  const scrollToCard = (cardRef) => {  
    if (cardRef && cardRef.current) {  
      // 滚动到目标Card的顶部位置  
      window.scrollTo({  
        top: cardRef.current.offsetTop - 70, // 减去一些值以考虑导航栏或顶部其他元素的高度  
        behavior: 'smooth', // 平滑滚动  
      });  
    }  
  };  

  // Steps的onChange事件处理函数  
  const handleStepChange = (nextStep) => {  
    setCurrentStep(nextStep);  
    // 根据步骤索引滚动到对应的Card  
    switch (nextStep) {  
      case 0:  
        scrollToCard(cardRef1);  
        break;  
      case 1:  
        scrollToCard(cardRef2);  
        break;  
      case 2:  
        scrollToCard(cardRef3);  
        break;  
      case 3:  
        scrollToCard(cardRef4);  
        break;  
      default:  
        break;  
    }  
  };  

  const columns: any = [
    {
      title: t('ing.fileName'),
      dataIndex: 'fileName',
      key: 'filename',
      width: 100,
      fixed:'left',
      render: (text, record) => (  
        <>  
            {/* <span  onClick={() => window.open('/res-dir/Articel/Screen/' + item.filename, '_blank')}>{record.filename}</span> */}
            <a href={record.filename?('/res-dir/Articel/Original/'+record.filename):''} target="_blank" className="buttonText">{record.filename}</a>
        </>  
      ), 
    },
    {
      title: t('ing.citationCIR'),
      dataIndex: 'dateReference',
      width: 100,
      key: 'dateReference',
      ellipsis: {
        showTitle: false,
      },
      render: (dateReference) => (
        <Tooltip placement="topLeft" title={dateReference}>
          {dateReference}
        </Tooltip>
      ),
    },
    {
      title: t('ing.citationLiterature'),
      dataIndex: 'reference',
      width: 120,
      key: 'reference',
      ellipsis: {
        showTitle: false,
      },
      render: (reference) => (
        <Tooltip placement="topLeft" title={reference}>
          {reference}
        </Tooltip>
      ),
    },
    {
      title: t('ing.fullReference'),
      dataIndex: 'fullReference',
      width: 120,
      key: 'fullReference',
      ellipsis: {
        showTitle: false,
      },
      render: (fullReference) => (
        <Tooltip placement="topLeft" title={fullReference}>
          {fullReference}
        </Tooltip>
      ),
    },
    {
      title: t('ing.combineReference'),
      dataIndex: 'combineReference',
      key: 'combineReference',
      width:120,
      ellipsis: {
        showTitle: false,
      },
      render: (combineReference) => (
        <Tooltip placement="topLeft" title={combineReference}>
          {combineReference}
        </Tooltip>
      ),
    },
    {
      title: t('status'),
      dataIndex: 'status',
      key: 'status',
      ellipsis: {
        showTitle: false,
      },
      render: (status) => (
        <Tooltip placement="topLeft" title={status}>
          {status}
        </Tooltip>
      ),
    },
    {
      title: t('ing.decisionRead'),
      dataIndex: 'decisionRead',
      key: 'decisionRead',
      width:120,
      ellipsis: {
        showTitle: false,
      },
      render: (decisionRead) => (
        <Tooltip placement="topLeft" title={decisionRead}>
          {decisionRead}
        </Tooltip>
      ),
    },
    {
      title: t('ing.origin'),
      dataIndex: 'origin',
      key: 'origin',
      ellipsis: {
        showTitle: false,
      },
      render: (origin) => (
        <Tooltip placement="topLeft" title={origin}>
          {origin}
        </Tooltip>
      ),
    },
    {  
      title: t('action'),  
      key: 'action',
      fixed:'right',
      render: (text, record) => (  
        <>  
          {viewStatus ? null : (
            <>
                <Button type="link" onClick={() => handleEditReport(record)}>  
                  {t('edit')}  
                  </Button>  
                  <Button type="link" danger onClick={() => handleDeleteReport(record.id)}>  
                  {t('delete')}   
                  </Button> 
            </>
          )}
          
   
        </>  
      ),  
    },  
  ];

  const columns2: any = [
    {
      title: t('fulu'),
      dataIndex: 'fulu',
      key: 'fulu',
      width: 130,
      fixed:'left',
      render: (text, record) => (  
        <>  
            <span>{record.remark}</span>
        </>  
      ), 
    },
    {
      title: t('status'),
      dataIndex: 'status',
      key: 'status',
    },
    {
      title: t('ing.fileName'),
      dataIndex: 'filename',
      key: 'filename',
      width:120,
    },
    {  
      title: t('action'),  
      key: 'action',
      fixed:'right',
      render: (text, record) => (  
        <>  
          {viewStatus ? null : (
            <>
              <Button type="link" onClick={() => handleEditFulu(record)}>  
              {t('edit')}  
              </Button>  
              <Button type="link" danger onClick={() => handleDeleteFulu(record.id)}>  
              {t('delete')}   
              </Button>  
            </>
          )}
        
   
        </>  
      ),  
    },  
  ];

  const formColumns = []

  const handleAdd = () =>{
    SetisView(false)
    form2.resetFields()
    setTitle("新增/New")
    showModal()
  }

  const showModal = () => {  
    setIsModalVisible(true);  
  };  

  const handleEdit = (record) =>{
    SetisView(false)
    setTitle("修改/Edit")
    console.log(record,'record')
    form2.setFieldsValue({ ...record });  
    setIsModalVisible(true);  
    // 这里可以添加打开模态框并显示编辑表单的逻辑  
  }

  const handleDelete = (key) =>{
    let inciIds = []
    inciIds.push(key)
    Modal.confirm({  
      title: 'Confirm Delete',  
      content: 'Please confirm to DELETE SELECTED RECORDS!',  
      onOk() {  
        del(inciIds).then(res=>{
            message.success("Success")
            setReloadNum(Date.now())
        }) 
      },  
    }); 
  }

  const handleOk = () => {  
    // 调用接口添加数据，这里假设你有一个函数addFormData来处理添加逻辑  
    // const response = addFormData(newFormData);  
    // ...处理接口响应...  
    const values = form.getFieldsValue();  
    if(Title=='新增/New'){
        //新增
        values.id =null
        add(values).then(res=>{
            message.success("Success")
            setReloadNum(Date.now())
             // 假设添加成功，关闭弹窗  
            setIsModalVisible(false);  
        }).catch(()=>{
           
        })
    }else{
        //修改
        edit(values).then(res=>{
            message.success("Success")
            setReloadNum(Date.now())
             // 假设添加成功，关闭弹窗  
            setIsModalVisible(false);  
        }).catch(()=>{
       })
    }

  
    // 根据需要更新formData或执行其他逻辑  
    // ...  
  };  

  const handleCancel = () => {  
    setIsModalVisible(false);  
  };  

  //select查询

  const [searchResult, setSearchResult] = useState([]);  
  const [visible, setVisible] = useState(false);  
  const [selectedResult, setSelectedResult] = useState(null);  
  
  const handleSearch = (values) => {  
    // 假设这里有一个异步的搜索函数，它返回搜索结果  
    const fakeSearch = async () => {  
      const inci = form.getFieldsValue()
      const data={
        page:1,
        limit:999,
        search:inci.inciStr,
    }
    list(data).then(res=>{
        let incis=res.data.data.page
        // deepcode ignore CallbackShouldReturn: <please specify a reason of ignoring this>
        incis.map(item=>{
          item.name=(item.inciCn?''+item.inciCn:'') + (item.inciUs?' ,'+item.inciUs:'')
        })
        setSearchResult(incis);
        setVisible(true);  
    })
    };  
    fakeSearch()
  };  
  
  const handleSelectResult = (result) => {  
    form.setFieldsValue({ inciStr: result.name }); // 回填表单  
    form.setFieldsValue({lawInciSerial:result.serial})
    form.setFieldsValue({inciCn:result.inciCn})
    form.setFieldsValue({inciUs:result.inciUs})
    form.setFieldsValue({ingredient:result.inciUs})
    form.setFieldsValue({ingredientName:result.inciUs})
    setSelectedResult(result);  
    setVisible(false); // 关闭弹窗  
  };  
  
  const modalFooter = [  
    <Button key="back" onClick={() => setVisible(false)}>  
      取消  
    </Button>,  
    
  ];  

   // 初始化数据  
   useEffect(() => {  
    getData() 
    getInfo().then(res=>{
      console.log(res,'res')
      let data = res.data
      data.roles.forEach((item)=>{
        if(item == "Formulator"){
          setViewStatus(true)
        }
      })
    }) 
  }, []);  

  const getData = async () => {
    const id  =  getQueryVariable("id")
    const isview  =  getQueryVariable("view").toString()
    if(isview=='1'){
       SetisView(true)
    }else{
        SetisView(false)
    }
    if(id){
        setFormId(id)
        getIngredientSubjectTestById(id).then(response=>{
          const newUniqueSubjectLevels = new Set();  
              let data1 =response.data.data
              setTabData(data1)
              data1.forEach(item => {  
                item.subjectTestRespList.forEach(subItem => {  
                  const subjectLevel = `${subItem.zySafetySubjectDef.subjectLevel1Cn}/${subItem.zySafetySubjectDef.subjectLevel1En}`;  
                  newUniqueSubjectLevels.add(subjectLevel); // 使用Set来自动去重  
                });  
              });  
        const uniqueSubjectLevelsArray = Array.from(newUniqueSubjectLevels); 
        setTabSubjectLevel1(uniqueSubjectLevelsArray);
      }) 
        getIngredientInfoById(id).then(res=>{
            setReportlist(res.data.data.reports)
            setScreenlist(res.data.data.reportScreens)
            setRemarkslist(res.data.data.remarks)
            let reportData = res.data.data.reports
            // deepcode ignore CallbackShouldReturn: <please specify a reason of ignoring this>
            reportData.map(item=>{
                if(item.origin == 'CIR' || item.origin ==''){
                 
                }else{
                    item.combineReference=item.reference
                }
            })
            form.setFieldsValue({
                reports:res.data.data.reports,
            })
          if(res.data.data.description==null || res.data.data.description==""){
            form.setFieldsValue({
                description:"",
            })
          }else{
            form.setFieldsValue({
                description: res.data.data.description.split(',')
            })
          }
          setZYNo(res.data.data.zyNo)
        form.setFieldsValue({
            id :res.data.data.id,
            ingredient:res.data.data.ingredient,
            lawInciSerial:res.data.data.lawInciSerial,
            inciUs :res.data.data.inciUs,
            inciCn : res.data.data.inciCn,
            finding:res.data.data.finding,
            conclusionCn:res.data.data.conclusionCn,
            conclusion:res.data.data.conclusion,
            source:res.data.data.source,
            max3yearRinseoff :res.data.data.max3yearRinseoff,
            max3yearLeaveon:res.data.data.max3yearLeaveon,
            safetyConclusion:res.data.data.safetyConclusion,
            updateBy:res.data.data.updateBy,
            remark:res.data.data.remark,
            zyNo:res.data.data.zyNo,
            colour:res.data.data.colour,
        })
         if(res.data.citation==""|| res.data.citation==null || res.data.citation==undefined){
         }else{
            form.setFieldsValue({
                citation:res.data.data.citation.split('>>>')
            })
         }
        })
    }else{
      form.setFieldsValue(formCache)
    }
  } 

  //附录
  const handleAddFulu = () =>{
    let data = form.getFieldsValue()
    if(data.ingredient == null || data.ingredient == "" || data.ingredient == undefined){
      message.error("Please Add Ingredient")
    }else{  
      if( data.description=="" ||  data.description==undefined ||  data.description==null){
       
      }else{
        data.description=data.description.join(",");
      }
      if(data.citation =="" || data.citation ==undefined || data.citation == null){
    
      }else{
        data.citation = data.citation.join('>>>')
      }
      if(data.id == null || data.id == undefined || data.id ==""){
        add(data).then(response => {
          let newData = response.data.data
          if (response.data.status == 0) {
            setFormId(response.data.data.id)
            setZYNo(response.data.data.zyNo)
            if(newData.description==null || newData.description==""){
              newData.description=""
            }else{
              newData.description = newData.description.split(',')
            }
            form.setFieldsValue(newData)
            formFulu.resetFields()
            setFuluVisible(true); 
          }else{
            message.error(response.data.data)
          }
        })
      }else{
        formFulu.resetFields()
        setFuluVisible(true); 
      }

    }
  }

  const handleEditFulu = (record) =>{
    formFulu.setFieldsValue({ ...record });  
    setFuluVisible(true);  
    // 这里可以添加打开模态框并显示编辑表单的逻辑  
  }

  const handleDeleteFulu= (key) =>{
    let inciIds = []
    inciIds.push(key)
    Modal.confirm({  
      title: 'Confirm Delete',  
      content: 'Please confirm to DELETE SELECTED RECORDS!',  
      onOk() {  
        delRemark(inciIds).then(res=>{
            getIngredientInfoById(formId).then(res=>{
              setReportlist(res.data.data.reports)
              setScreenlist(res.data.data.reportScreens)
              setRemarkslist(res.data.data.remarks)
              let reportData = res.data.data.reports
              // file deepcode ignore CallbackShouldReturn: <please specify a reason of ignoring this>
              reportData.map(item=>{
                  if(item.origin == 'CIR' || item.origin ==''){
                  //  null
                  }else{
                      item.combineReference=item.reference
                  }
              })
              form.setFieldsValue({
                  reports:res.data.data.reports,
              })
              message.success("success")
             }) 
        }) 
      },  
    }); 
  }

  
  const handleFuluOk = () => {  
    formFulu.validateFields().then(values => {  
      console.log('Received values of form:', values);  
      // 在这里处理表单数据，比如发送到服务器  
      let formData = formFulu.getFieldsValue()
      if(formData.id == undefined || formData.id == null || formData.id ==""){
        formData.safetyIngredientZyNo =zyNo
        addRemark(formData).then(res1=>{
          getIngredientInfoById(formId).then(res=>{
            setReportlist(res.data.data.reports)
            setScreenlist(res.data.data.reportScreens)
            setRemarkslist(res.data.data.remarks)
            let reportData = res.data.data.reports
            reportData.map(item=>{
                if(item.origin == 'CIR' || item.origin ==''){
                //  null
                }else{
                    item.combineReference=item.reference
                }
            })
            form.setFieldsValue({
                reports:res.data.data.reports,
            })
            message.success("success")
            setFuluVisible(false)
           }) 
       })
    }else{
      updateRemark(formData).then(res1=>{
        getIngredientInfoById(formId).then(res=>{
          setReportlist(res.data.data.reports)
          setScreenlist(res.data.data.reportScreens)
          setRemarkslist(res.data.data.remarks)
          let reportData = res.data.data.reports
          reportData.map(item=>{
              if(item.origin == 'CIR' || item.origin ==''){
              //  null
              }else{
                  item.combineReference=item.reference
              }
          })
          form.setFieldsValue({
              reports:res.data.data.reports,
          })
          message.success("success")
          setFuluVisible(false)
         })
     })
   }
      // 关闭弹窗  
      setFuluVisible(false);  
    }).catch(info => {  
      console.log('Validate Failed:', info);  
    });  
  }; 

  const handleFuluCancel = () => {  
    setFuluVisible(false);  
  };  

  //文献
  const handleAddReport = () =>{
    let data = form.getFieldsValue()
    if(data.ingredient == null || data.ingredient == "" || data.ingredient == undefined){
      message.error("Please Add Ingredient")
    }else{  
      if( data.description=="" ||  data.description==undefined ||  data.description==null){
       
      }else{
        data.description=data.description.join(",");
      }
      if(data.citation =="" || data.citation ==undefined || data.citation == null){
    
      }else{
        data.citation = data.citation.join('>>>')
      }
      if(data.id == null || data.id == undefined || data.id ==""){
        add(data).then(response => {
          let newData = response.data.data
          if (response.data.status == 0) {
            setFormId(response.data.data.id)
            setZYNo(response.data.data.zyNo)
            if(newData.description==null || newData.description==""){
              newData.description=""
            }else{
              newData.description = newData.description.split(',')
            }
            form.setFieldsValue(newData)
            formReport.resetFields()
           setReportVisible(true); 
          }else{
            message.error(response.data.data)
          }
        })
      }else{
        formReport.resetFields()
        setReportVisible(true); 
      }

    }
  
  }

  const handleEditReport = (record) =>{
    formReport.setFieldsValue({ ...record });  
    setReportVisible(true);  
    // 这里可以添加打开模态框并显示编辑表单的逻辑  
  }

  const handleDeleteReport = (key) =>{
    let inciIds = []
    inciIds.push(key)
    Modal.confirm({  
      title: 'Confirm Delete',  
      content: 'Please confirm to DELETE SELECTED RECORDS!',  
      onOk() {  
        delReport(inciIds).then(res=>{
            getIngredientInfoById(formId).then(res=>{
              setReportlist(res.data.data.reports)
              setScreenlist(res.data.data.reportScreens)
              setRemarkslist(res.data.data.remarks)
              let reportData = res.data.data.reports
              reportData.map(item=>{
                  if(item.origin == 'CIR' || item.origin ==''){
                  //  null
                  }else{
                      item.combineReference=item.reference
                  }
              })
              form.setFieldsValue({
                  reports:res.data.data.reports,
              })
              message.success("success")
             }) 
        }) 
      },  
    }); 
  }

  const handleReportOk = () => {  
    formReport.validateFields().then(values => {  
      console.log('Received values of form:', values);  
      // 在这里处理表单数据，比如发送到服务器  
      let formData = formReport.getFieldsValue()
      if(formData.id == undefined || formData.id == null || formData.id ==""){
        if(formData.origin == 'CIR'){
          let data={
            report:{
               filename:formData.filename,
               dateReference: formData.dateReference,
               status:formData.status,
               decisionRead:formData.decisionRead,
               link: formData.link,
               origin:formData.origin,
               combineReference:formData.combineReference,
               fullReference:formData.fullReference,
               }
            }
          addReport(formId,data).then(response => {
            getIngredientInfoById(formId).then(res=>{
            setReportlist(res.data.data.reports)
            setScreenlist(res.data.data.reportScreens)
            setRemarkslist(res.data.data.remarks)
            let reportData = res.data.data.reports
            reportData.map(item=>{
                if(item.origin == 'CIR' || item.origin ==''){
                //  null
                }else{
                    item.combineReference=item.reference
                }
            })
            form.setFieldsValue({
                reports:res.data.data.reports,
            })
            message.success("success")
            setReportVisible(false)
           }) 
         });
        }else{
          let data={
            report:{
               filename:formData.filename,
               reference: formData.dateReference,
               status:formData.status,
               decisionRead:formData.decisionRead,
               link: formData.link,
               origin:formData.origin,
               combineReference:formData.combineReference,
               fullReference:formData.fullReference,
               }
            }
          addReport(formId,data).then(response => {
            getIngredientInfoById(formId).then(res=>{
              getIngredientInfoById(formId).then(res=>{
                setReportlist(res.data.data.reports)
                setScreenlist(res.data.data.reportScreens)
                setRemarkslist(res.data.data.remarks)
                let reportData = res.data.data.reports
                reportData.map(item=>{
                    if(item.origin == 'CIR' || item.origin ==''){
                    //  null
                    }else{
                        item.combineReference=item.reference
                    }
                })
                form.setFieldsValue({
                    reports:res.data.data.reports,
                })
            message.success("success")
            setReportVisible(false)
           }) 
         });
        }) 
      }
    }else{
      if(formData.origin == 'CIR'){
        let data={
          id: formData.id,
          ...{
             filename:formData.filename,
             dateReference: formData.dateReference,
             status:formData.status,
             decisionRead:formData.decisionRead,
             link: formData.link,
             origin:formData.origin,
             combineReference:formData.combineReference,
             fullReference:formData.fullReference,
             }
          }
       editReport(data).then(response => {
        getIngredientInfoById(formId).then(res=>{
          setReportlist(res.data.data.reports)
          setScreenlist(res.data.data.reportScreens)
          setRemarkslist(res.data.data.remarks)
          let reportData = res.data.data.reports
          reportData.map(item=>{
              if(item.origin == 'CIR' || item.origin ==''){
              //  null
              }else{
                  item.combineReference=item.reference
              }
          })
          form.setFieldsValue({
              reports:res.data.data.reports,
          })
          message.success("success")
          setReportVisible(false)
         }) 
       });
      }else{
        let data={
          id: formData.id,
          ...{
             filename:formData.filename,
             reference: formData.dateReference,
             status:formData.status,
             decisionRead:formData.decisionRead,
             link: formData.link,
             origin:formData.origin,
             combineReference:formData.combineReference,
             fullReference:formData.fullReference,
             }
          }
       editReport(data).then(response => {
        getIngredientInfoById(formId).then(res=>{
          setReportlist(res.data.data.reports)
          setScreenlist(res.data.data.reportScreens)
          setRemarkslist(res.data.data.remarks)
          let reportData = res.data.data.reports
          reportData.map(item=>{
              if(item.origin == 'CIR' || item.origin ==''){
              //  null
              }else{
                  item.combineReference=item.reference
              }
          })
          form.setFieldsValue({
              reports:res.data.data.reports,
          })
          message.success("success")
          setReportVisible(false)
         }) 
       });
      }
      }
      // 关闭弹窗  
      setReportVisible(false);  
    }).catch(info => {  
      console.log('Validate Failed:', info);  
    });  
  }; 

  const handleReportCancel = () => {  
    setReportVisible(false);  
  };  

  const handleFileChange = (info) => { 
    console.log(info,'info')
    info.file.status = "done"
    const file = info.fileList[0].originFileObj
    let formData = new FormData();
    formData.append("file", file);
    let target = "Articel/Original"//存放文件路径
    formData.append("target", target);
    console.log(formData,'file')
    upload(formData).then(res=>{
       if (res.data.status == 0) {
          // link.value = data;
          formReport.setFieldsValue({
            filename:file.name
          })
       } else {
         message.error("error!")
       }
    })
  };  

  const historyTags = useHistoryTags()
  const cache = useDynamicCache()

  const submitFormCancel = () =>{
    console.log(currentPage,'currentPage')
    const data = historyTags.routeDelTags(currentPage.currentName);
    // cache.reset(currentPage.currentName);
    cache.remove('LiterdataDetail$-$table-literdataDetail-formCache')
    if(data) navigate(data.path)

  }

  const submitForm = () =>{
    let data = form.getFieldsValue()

    if( data.description=="" ||  data.description==undefined ||  data.description==null){
        data.description=""
      }else{
        data.description=data.description.join(",");
      }
      if(data.citation =="" || data.citation ==undefined || data.citation == null){
        data.citation=""
      }else{
        data.citation = data.citation.join('>>>')
      }
       if (data.id != undefined) {
         edit(data).then(response => {
          if(response.data.status == 500){
            message.error(response.data.data)
            if( data.description=="" ||  data.description==undefined ||  data.description==null){

            }else{
              data.description= data.description.split(',')
            }
            if(data.citation =="" || data.citation ==undefined || data.citation == null){
    
            }else{
              data.citation = data.citation.split('>>>')
            }
          }else{
            message.success("Success")
            const data = historyTags.routeDelTags(currentPage.currentName);
            cache.reset(currentPage.currentName);
            if(data) navigate(data.path)
          }
                //    const obj = { path: "/safety/literdata" , query: { t: Date.now() }};
                //     proxy.$tab.closeOpenPage(obj);
         });
       }else{
        add(data).then(response => {
          if(response.data.status == 500){
            message.error(response.data.data)
            if( data.description=="" ||  data.description==undefined ||  data.description==null){
              
            }else{
              data.description= data.description.split(',')
            }
            if(data.citation =="" || data.citation ==undefined || data.citation == null){
    
            }else{
              data.citation = data.citation.split('>>>')
            }
          }else{
            message.success("Success")
            const data = historyTags.routeDelTags(currentPage.currentName);
            cache.reset(currentPage.currentName);
            if(data) navigate(data.path)
          }
        
                //    form.value=response.data
                //    const obj = { path: "/safety/literdata" , query: { t: Date.now() }};
                //     proxy.$tab.closeOpenPage(obj);
         });
       }
  }

  const CustomTitleWithButton = ({ title, onClick }) => (  
    <div style={{ display: 'flex', alignItems: 'center' }}>  
      <span>{title}</span>  
      <Button style={{ marginLeft: '8px' }} onClick={submitFormCancel}>  
        {t('cancel')}  
      </Button>  
    </div>  
  ); 

  const onValuesChange=(changedValues, allValues)=>{
    console.log(changedValues.nameCn,'changedValues')
    console.log(allValues,'allValues')
    const data = allValues
    setformCache(data)
  }

  const renderOperator = <>
  <Button type="primary" size="small" onClick={handleAdd}>{t('add')}</Button>
</>
  
  return (  
    <div>  
      <Row justify="space-between" align="top">  
        <Col span={4} style={{ position: 'relative' }}>  
        <div  
            style={{  
              position: 'fixed',  
              top: 120, // 从顶部开始粘住  
              zIndex: 1, // 确保在其他内容之上  
              backgroundColor: 'white',  
              padding: '10px', // 可选内边距  
              // 可以添加maxHeight和overflowY来处理内容过多时的情况  
            }}  
          >  
          <Steps direction="vertical" current={currentStep} onChange={handleStepChange}>  
            {maodianlist.map((item, index) => (  
              <Step key={index} title={item} />  
            ))}  
          </Steps>  
          </div>
        </Col>  
        <Col span={20}>  
          {/* 第一个Card：表单 */}  
          <Card ref={cardRef1} title={  
          <CustomTitleWithButton  
        title={maodianlist[0]}  
        onClick={submitFormCancel}  
      />  
    }>  
          <Form form={form} layout="vertical" onValuesChange={onValuesChange}>
            <Form.Item  
                name="id"  
                label="id" 
                hidden 
            >  
                <Input disabled/>  
            </Form.Item> 
            {/* 这里假设添加的内容也是一个对象，包含key和value */}  
            <Form.Item name="inciStr" label="INCI">  
        <Input />  
      </Form.Item>  
      <Form.Item>  
        <Button type="primary" htmlType="submit" onClick={handleSearch}>  
          根据INCI搜索  
        </Button>  
      </Form.Item>  
      <Modal  
        title="搜索结果"  
        visible={visible}  
        onCancel={() => setVisible(false)}  
        footer={modalFooter}  
      >  
        <List  
          itemLayout="horizontal"  
          dataSource={searchResult}  
          renderItem={(item) => (  
            <List.Item  
              actions={[  
                <Button type="link" onClick={() => handleSelectResult(item)}>  
                  选择  
                </Button>,  
              ]}  
            >  
              <List.Item.Meta  
                title={<span>{item.name}</span>}  
              />  
            </List.Item>  
          )}  
        />  
      </Modal>  
            <Form.Item  
              name="lawInciSerial"  
              label={t('ing.lawInciSerial')}
            >  
              <Input disabled={isView}/>  
            </Form.Item>  
            <Form.Item  
              name="ingredient"  
              label={t('Ingredient')}
            >  
              <Input disabled={isView}/>  
            </Form.Item> 
            <Form.Item  
              name="ingredientName"  
              label={t('Ingredient')}
              hidden
            >  
              <Input disabled={isView}/>  
            </Form.Item>
            <Form.Item  
              name="inciCn"  
              label={t('ing.inciCn')}
            >  
              <Input disabled/>  
            </Form.Item>  
            <Form.Item  
              name="inciUs"  
              label={t('ing.inciUs')}  
            >  
              <Input disabled/>  
            </Form.Item>  
            <Form.Item  
              name="finding"  
              label={t('ing.finding')}  
            >  
              <Input disabled={isView}/>  
            </Form.Item>  
            <Form.Item  
              name="description"  
              label={t('ing.description')}  
            >  
                <Select mode="tags">  
                    <Option value="其他">其他</Option>  
                    <Option value="刺激性">刺激性</Option>  
                    <Option value="致敏性">致敏性</Option>  
                </Select>  
            </Form.Item>  
            <Form.Item  
              name="conclusion"  
              label={t('ing.conclusion')}  
            >  
              <Input.TextArea disabled={isView}/>  
            </Form.Item>
            <Form.Item  
              name="conclusionCn"  
              label={t('ing.conclusionCn')}  
            >  
              <Input.TextArea disabled={isView}/>  
            </Form.Item>  
            <Form.Item  
              name="source"  
              label={t('ing.source')}  
            >  
              <Input.TextArea disabled={isView}/>  
            </Form.Item>  
            <Form.Item  
              name="remark"  
              label={t('ing.remark')}  
            >  
              <Input.TextArea disabled={isView}/>  
            </Form.Item>  
            <Form.Item  
              name="max3yearLeaveon"  
              label={t('ing.max3yearLeaveon')}  
            >  
              <Input disabled={isView}/>  
            </Form.Item>  
            <Form.Item  
              name="max3yearRinseoff"  
              label={t('ing.max3yearRinseoff')}  
            >  
              <Input disabled={isView}/>  
            </Form.Item>
            <Form.Item  
              name="safetyConclusion"  
              label={t('ing.safetyConclusion')}  
            >  
              <Input disabled={isView}/>  
            </Form.Item>
            <Form.Item  
              name="citation"  
              label={t('ing.citation')}  
            >  
              <Select mode='tags' disabled={isView}/>  
            </Form.Item>
            <Form.Item  
              name="updateBy"  
              label={t('ing.updateBy')}  
            >  
              <Input disabled={isView}/>  
            </Form.Item>
            <Form.Item  
              name="colour"  
              label={t('ing.colour')}  
            >  
              <Select>  
                    <Option value="PURPLE">PURPLE</Option>  
                    <Option value="BLUE">BLUE</Option>  
                    <Option value="SKYBLUE">SKYBLUE</Option>  
                    <Option value="LIGHTGREEN">LIGHTGREEN</Option>  
                    <Option value="GREEN">GREEN</Option>  
                    <Option value="GREENYELLOW">GREENYELLOW</Option> 
                    <Option value="YELLOW">YELLOW</Option>  
                    <Option value="ORANGE">ORANGE</Option>  
                    <Option value="ORANGERED">ORANGERED</Option>  
                    <Option value="RED">RED</Option>  
                </Select>  
            </Form.Item>
          </Form>  
          </Card>  
          {/* 第二个Card：表格 */}  
          <Card title={maodianlist[1]} ref={cardRef2} style={{marginTop:'2%'}}>
          <div style={{ marginBottom: '16px' }}>  
            <Button disabled={viewStatus} type="primary" onClick={handleAddReport}>{t('add')}</Button>  
            </div>    
          <Table  
                  dataSource={reportlist} // 筛选与 subjectLevel 匹配的数据  
                  columns={columns}  
                  rowKey={(record) => record.id} // 假设每条记录都有一个唯一的id  
                  pagination={false}
                  bordered  
                  scroll={{ x: '1100px' }} // 或者使用具体的像素值，如 '1000px' 
                />  
          </Card>  
      <Modal  
        title='Upload'// 假设您有一个对应的国际化字符串  
        visible={reportvisible}  
        onOk={handleReportOk}  
        onCancel={handleReportCancel}  
        destroyOnClose
      >  
        <Form  
          form={formReport}  
          layout="vertical"  
          name="addReportForm"  
          initialValues={{ remember: true }}  
        >  
         <Form.Item  
                name="id"  
                label="id" 
                hidden 
            >  
                <Input disabled/>  
            </Form.Item> 
          <Form.Item  
            label={t('ing.fileName')} // 假设您有一个对应的国际化字符串  
            name="filename"  
          >  
             <Upload  
                customRequest={({ file, onSuccess, onError }) => {  
                  // 这里是自定义上传逻辑，您可以根据实际需求实现上传逻辑  
                  // 例如，使用axios发送POST请求上传文件  
                  // 注意：这里的逻辑与表单提交时的文件上传是独立的，如果只需要在表单提交时上传，可以省略这部分  
                }}  
                onChange={handleFileChange} 
              >  
                <Button icon={<UploadOutlined />}>{t('selectUpload')}</Button>  
              </Upload> 
          </Form.Item>  
          <Form.Item  
            label={t('ing.dateReference')} // 假设您有一个对应的国际化字符串  
            name="dateReference"  
 
          >  
            <Input />  
          </Form.Item> 
          <Form.Item  
            label={t('ing.fullReference')} // 假设您有一个对应的国际化字符串  
            name="fullReference"  

          >  
            <Input.TextArea />  
          </Form.Item> 
          <Form.Item  
            label={t('ing.combineReference')} // 假设您有一个对应的国际化字符串  
            name="combineReference"  
 
          >  
            <Input.TextArea />  
          </Form.Item> 
          <Form.Item  
            label={t('status')} // 假设您有一个对应的国际化字符串  
            name="status"  

          >  
            <Input />  
          </Form.Item> 
          <Form.Item  
            label={t('ing.decisionRead')} // 假设您有一个对应的国际化字符串  
            name="decisionRead"  
          
          >  
            <Select>  
                    <Option value="1">1</Option>  
                    <Option value="0">0</Option>  
                </Select> 
          </Form.Item> 
          <Form.Item  
            label={t('ing.origin')} // 假设您有一个对应的国际化字符串  
            name="origin"  
          >  
             <Select>  
                    <Option value="Literature">Literature</Option>  
                    <Option value="CIR">CIR</Option>  
                </Select>   
          </Form.Item>
          {/* 可以添加更多表单项 */}  
        </Form>  
      </Modal> 
          {/* 第三个Card：表格（和第二个类似，但可能数据不同） */}  
          <Card title={maodianlist[2]} ref={cardRef3} style={{marginTop:'2%'}}> 
          <div style={{ marginBottom: '16px' }}>  
            <Button disabled={viewStatus} type="primary"  onClick={handleAddFulu}>{t('add')}</Button>  
            </div>  
          <Table  
                  size='small'
                  dataSource={remarkslist} // 筛选与 subjectLevel 匹配的数据  
                  columns={columns2}  
                  rowKey={(record) => record.id} // 假设每条记录都有一个唯一的id  
                  pagination={false}
                  bordered  
                  scroll={{ x: 'max-content' }} // 或者使用具体的像素值，如 '1000px' 
                /> 
          </Card>  
          <Modal  
        title='Upload'// 假设您有一个对应的国际化字符串  
        visible={fuluvisible}  
        onOk={handleFuluOk}  
        onCancel={handleFuluCancel}  
      >  
        <Form  
          form={formFulu}  
          layout="vertical"  
          name="addReportForm"  
          initialValues={{ remember: true }}  
        >  
         <Form.Item  
                name="id"  
                label="id" 
                hidden 
            >  
                <Input disabled/>  
            </Form.Item> 
           
          <Form.Item  
            label={t('fulu')} // 假设您有一个对应的国际化字符串  
            name="remark"  
 
          >  
            <Input.TextArea />  
          </Form.Item> 
          <Form.Item  
            label={t('status')} // 假设您有一个对应的国际化字符串  
            name="status"  

          >  
            <Input />  
          </Form.Item> 
          <Form.Item  
            label={t('ing.fileName')} // 假设您有一个对应的国际化字符串  
            name="filename"  
 
          >  
            <Input disabled/>  
          </Form.Item> 
         
          {/* 可以添加更多表单项 */}  
        </Form>  
      </Modal> 
          {/* 第四个Card：文字内容 */}  
          <Card title={maodianlist[3]} ref={cardRef4} style={{marginTop:'2%'}}>
          {tabData.length>0 && (  
                <MyTabsComponent tabData={tabData} tabSubjectLevel1={tabSubjectLevel1} formId={formId}  reportList={reportlist}/>  
            )} 
         
          </Card> 
          {/* 在这里放置保存按钮 */}  
          <div style={{ textAlign: 'left', marginTop: '16px' }}>  
                <Button disabled={viewStatus} type="primary" onClick={() => { submitForm() }}>  
                  {t('save')}  
                </Button>  
                <Button style={{marginLeft:'2%'}} onClick={() => { submitFormCancel() }}>  
                  {t('cancel')}  
                </Button> 
           </div>     
        </Col>  
      </Row> 
      <Modal  
          title={Title}
          visible={isModalVisible}  
          onOk={handleOk}  
          onCancel={handleCancel}  
        >  
          <Form form={form2} layout="vertical">
            <Form.Item  
                name="id"  
                label="id" 
                hidden 
            >  
                <Input disabled/>  
            </Form.Item> 
            {/* 这里假设添加的内容也是一个对象，包含key和value */}  
            <Form.Item  
              name="annex"  
              label={t('tspec2015.annex')}
              rules={[{ required: true, message: '请输入附表！' }]}    
            >  
              <Input disabled={isView}/>  
            </Form.Item>  
            <Form.Item  
              name="serial"  
              label={t('tspec2015.serial')}
              rules={[{ required: true, message: '请输入序号！' }]}    
            >  
              <Input disabled={isView}/>  
            </Form.Item>  
            <Form.Item  
              name="chemicalNameCn"  
              label={t('tspec2015.chemicalNameCn')}  
            >  
              <Input disabled={isView}/>  
            </Form.Item>  
            <Form.Item  
              name="chemicalNameEn"  
              label={t('tspec2015.chemicalNameEn')}  
            >  
              <Input disabled={isView}/>  
            </Form.Item>  
            <Form.Item  
              name="productTypeBodyPart"  
              label={t('tspec2015.productTypeBodyPart')}  
            >  
              <Input disabled={isView}/>  
            </Form.Item>  
            <Form.Item  
              name="maxConcentration"  
              label={t('tspec2015.maxConcentration')}  
            >  
              <Input disabled={isView}/>  
            </Form.Item>
            <Form.Item  
              name="other"  
              label={t('tspec2015.other')}  
            >  
              <Input disabled={isView}/>  
            </Form.Item>  
            <Form.Item  
              name="wordConditionUseWarning"  
              label={t('tspec2015.wordConditionUseWarning')}  
            >  
              <Input disabled={isView}/>  
            </Form.Item>  
            <Form.Item  
              name="color"  
              label={t('tspec2015.color')}  
            >  
              <Input disabled={isView}/>  
            </Form.Item>  
            <Form.Item  
              name="annexDetailDesc"  
              label={t('tspec2015.annexDetailDesc')}  
            >  
              <Input disabled={isView}/>  
            </Form.Item>  
          </Form>  
        </Modal>  

    </div>  
  );  
};  
  
export default LiterdataDetail;